package net.wangds.yunz.auth.service;

import net.wangds.yunz.auth.comp.AuthAccountComp;
import net.wangds.log.helper.LogHelper;
import net.wangds.program.auth.module.AuthAccount;
import net.wangds.spring.utils.SpringUtils;
import net.wangds.utils.JsonUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.context.annotation.Profile;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Optional;

@SuppressWarnings("unused")
@Service
@Primary
@Profile({"program"})
public class AuthUserDetailService implements UserDetailsService {

    @Autowired
    private AuthAccountComp mmCmpAcc;

    @Override
    public UserDetails loadUserByUsername(String loginname) throws UsernameNotFoundException {
        AuthAccount res;
        LogHelper.dev("加载用户信息："+loginname);
        Optional<AuthAccount> opt = mmCmpAcc.findNormalUserByLoginName(loginname);
        if(opt.isPresent()){
          res =   opt.get();
          LogHelper.dev("密码：");
            BCryptPasswordEncoder encoder = SpringUtils.getBean(BCryptPasswordEncoder.class);
            res.setPassword(encoder.encode(res.getPassword()));//给密码加密
            //LogHelper.dev(()->"加密后的密码："+res.getPassword());
        }else {
            String msg = SpringUtils.getMessage(
                    "mod_common_auth_user_not_found", loginname
            );
            LogHelper.dev(()->msg+",loginname = "+loginname);
            throw new UsernameNotFoundException(msg);
        }

        LogHelper.dev(()->"用户登录结果:"+ JsonUtils.toJsonStr(res));

        return res;
    }

    public Optional<AuthAccount> loadByLoginname(String loginname){
        return mmCmpAcc.findNormalUserByLoginName(loginname);
    }
}
